package com.hax2max.service;

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

import com.hax2max.control.DataHandler;
import com.hax2max.control.FriendStalkerException.IExternalClient;
import com.hax2max.model.FootPrint;

public class FootprintUpdater extends android.app.Service {
	private static final String TAG = "FootPrintUpdater";
	private TimerTask tt;
	private Timer engineTimer;
	private boolean running;
	private static DataHandler dh;
	private LocationManager lm;
	private LocationListener locListener;
	//delay and period in seconds
	private int delay = 60;
	private int period = 60;
	
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public void onCreate()
	{
		running=true;
		engineTimer = new Timer();
		scheduleUpdate();
		Log.v("SERVICE", "Servicen startad");
		
		initLm();
		
		
		
	}

	private void initLm() {
		
		locListener = new LocationListener() {
		     
			public void onLocationChanged(Location newLocation) {
				Log.v(TAG, "onLocationChanged");
			}
 
			public void onProviderDisabled(String arg0) {
				Log.v(TAG , "Provider disabled: " +arg0);
			}
 
			public void onProviderEnabled(String arg0) {
				Log.v(TAG, "Provider enabled: " + arg0);
			}
 
			public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
				Log.v(TAG, "onStatusChanged: " + arg0);
				
			}
		};
		lm = (LocationManager)getSystemService(
				Context.LOCATION_SERVICE);
		
		
		/*
		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		criteria.setAltitudeRequired(false);
		criteria.setBearingRequired(false);
		criteria.setCostAllowed(true);
		criteria.setPowerRequirement(Criteria.POWER_LOW);

		provider = lm.getBestProvider(criteria,true);*/
		if( lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2, 0,locListener);
		}else if(lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
			lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 2, 0,locListener); 
		}
		
		
	}

	private void scheduleUpdate() {
		tt=new EngineTimerTask();
		engineTimer.schedule(tt, delay * 1000, period * 1000); // schedule the timer to call EngineTimerTask at every 10 seconds
		
		
	}

	public static void setApp(DataHandler datahandler) {
		dh=datahandler;
				
	}
	
	@Override public void onDestroy() 
	{
		Log.v(TAG, "onDestroy called");  
		super.onDestroy();
		_shutdownService();
	}
	
	private void _shutdownService() {
		tt.cancel();
		running = false;
		Log.i(getClass().getSimpleName(), "Timer stopped!!!");
	}
	

	class EngineTimerTask extends TimerTask { 
		@Override
		public void run() {
			engine(); 
			} 
	} 
	
    public void engine() throws NullPointerException{ 
    	if (running)
    	{
    		   	if(dh == null)
    		   		dh = DataHandler.getInstance();
    			Log.v(TAG, "Running footprintUpdater");	
    		 	
	    		if( dh != null && dh.isLoggedIn() ) {
	    			Location currentLoc = null;
	    		
	    			if( lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
	    				currentLoc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);	
	    			}else if( lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER) ){
	    				currentLoc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
	    			}
	    			if(currentLoc != null) {
			    		int latitude= (int)(currentLoc.getLatitude()*1E6);
			    		int longitude= (int)(currentLoc.getLongitude()*1E6);
			    		
			    		FootPrint p= new FootPrint();
			    		p.latitude=latitude;
			    		p.longitude=longitude;
			    		p.timeStamp=Calendar.getInstance().getTime();
			    		dh.saveFootPrint(p);
					
			    		Log.v(TAG, "Storage of footprint complete");
						
			    		Log.v(TAG,"Requesting update from server");
			    		try {
							dh.updateFriendsList();
						} catch (IExternalClient e) {
							// TODO Auto-generated catch block
							Log.v(TAG,"Error uppdating friendslist: " + e.getMessage());
						}
	    			}
	    		}		    		
    	}
    	else
    		stopSelf();
    }
	
    
}
